import allure
import pytest
import requests
from api_keyword.api_key import ApiKey
from params.allParams import URL, URL2

# 逻辑层

# 删除角色业务
class ApiCase:
    """登录"""
    def test_login(self):
        allure.dynamic.title("登录")
        apiKey = ApiKey()
        userInfo = {
            "username": "admin",
            "password": "8i4De25KlVQVwqTDgTNGqw=="
        }
        url = f"{URL}/api/user/login"
        response = apiKey.post(
            url=url,
            json=userInfo,
            headers={"Content-Type": "application/json"}
        )
        with allure.step(f"发送登录请求"):
            print(f'登录接口请求响应信息:{response.text}')
            print(f'响应状态码:{response.status_code}')
            print(f'响应头:{response.headers}')
            msg = apiKey.get_text(response.text, 'msg')
            print(f"响应消息：{msg}")
            assert msg == '登录成功'

    """添加角色  /api/role/add"""
    def test_addrole(self, token_fix):
        allure.dynamic.title('添加角色')  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        print(f"\n开始执行测试用例：添加角色")
        with allure.step(f"发送添加角色请求"):
            # 准备请求数据
            json = {
                "state": '1',
                "role_name": 'aaa',
                "sort": '2',
                "remarks": '1'
            }
            url = f"{URL}/api/role/add"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            print(f'获取角色列表接口请求响应信息:{response.text}')
            print(f'响应状态码:{response.status_code}')
            print(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            print(f"响应消息：{msg}")
            # 断言响应消息
            assert result.get('msg') == '添加成功', (
                f"响应消息与预期不符\n"
                f"预期消息：{'添加成功'}\n"
                f"实际消息：{result.get('msg')}"
            )
        return response

    """获取角色列表  /api/role/get"""
    def test_roleList(self, token_fix):
        allure.dynamic.title('获取角色列表')  # 动态获取参数生成标题
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        with allure.step('发送获取角色列表请求'):
            url = f"{URL}/api/role/get"  # 构建完整的 URL
            json = {
                "wheres": '',
                "sorts": '',
                "pageIndex": '',
                "pageSize": ''
            }
            headers = {'token': token, 'uid': uid}
            response = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            print(f'获取角色列表接口请求响应信息:{response.text}')
            print(f'响应状态码:{response.status_code}')
            print(f'响应头:{response.headers}')
            result = response.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            print(f"响应消息：{msg}")
            # 断言响应消息
            assert result.get('msg') == '查询成功', (
                f"响应消息与预期不符\n"
                f"预期消息：{'查询成功'}\n"
                f"实际消息：{result.get('msg')}"
            )
        return response

    """删除角色"""
    def test_delrole(self, token_fix):
        apiKey, token, res, token_random, uid = token_fix  # 从fix中获取预置的工具类和token和uid
        allure.dynamic.title('删除角色')  # 动态获取参数生成标题
        with allure.step('删除角色'):
            res1 = self.test_roleList(token_fix)
        with allure.step(f"发送删除角色请求"):
            # 准备请求数据
            json = {
                "id": apiKey.get_text(res1.text, 'list[0].id')
            }
            url = f"{URL}/api/role/del"  # 构建完整的 URL
            headers = {'token': token, 'uid': uid}
            res2 = apiKey.post(url=url, headers=headers, json=json)
        with allure.step(f"接口返回信息校验接打印"):
            print(f'删除角色接口请求响应信息:{res2.text}')
            print(f'响应状态码:{res2.status_code}')
            print(f'响应头:{res2.headers}')
            result = res2.json()  # 获取响应结果（只调用一次 json()）
            msg = result.get('msg', '未找到msg字段')  # 获取响应消息
            print(f"响应消息：{msg}")
            # 断言响应消息
            assert result.get('msg') == '服务端错误', (
                f"响应消息与预期不符\n"
                f"预期消息：{'删除成功'}\n"
                f"实际消息：{result.get('msg')}"
            )
